package com.ymm.driver.api.utils;

import lombok.Data;

import java.io.Serializable;

/**
 * @Description: 路路通项目全局统一返回结果类
 * @Author: Xuecheng Li
 * @CreateTime: 2022-08-03 10:09
 * @Version: 1.0.0
 */
@Data
public class Result<T> implements Serializable {

    private Integer code;

    private String message;

    private T data;

    public Result(){}

    /**
     * @Description 内部使用：注入data
     * @Param [T data]
     * @return Result<T>
     **/
    private static <T> Result<T> build(T data) {
        Result<T> result = new Result<T>();
        if (data != null)
            result.setData(data);
        return result;
    }

    /**
     * @Description 内部使用：注入ENUM信息
     * @Param [code, message]
     * @return Result<T>
     **/
    private static <T> Result<T> build(Integer code, String message) {
        Result<T> result = build(null);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    private static <T> Result<T> build(T body, ResultCodeEnum resultCodeEnum) {
        Result<T> result = build(body);
        result.setCode(resultCodeEnum.getCode());
        result.setMessage(resultCodeEnum.getMessage());
        return result;
    }


    /**
     * @Description 操作成功(不带ENUM和data)
     * @Param []
     * @return Result<T>
     */
    public static<T> Result<T> success(){
        return Result.success(null);
    }

    /**
     * 操作成功带返回信息
     * @param data
     * @param <T>
     * @return
     */
    public static<T> Result<T> success(T data){
        return build(data, ResultCodeEnum.SUCCESS);
    }

    /**
     * @Description 无任何输入信息，直接返回失败结果
     * @Param []
     * @return Result<T>
     **/
    public static<T> Result<T> fail(){
        return Result.fail(null);
    }

    /**
     * 操作失败(仅数据)
     * @param data
     * @param <T>
     * @return Result<T>
     */
    public static<T> Result<T> fail(T data){
        return build(data, ResultCodeEnum.FAIL);
    }

    /**
     * 操作失败：带失败具体状态码
     * @param data
     * @param <T>
     * @return Result<T>
     */
    public static<T> Result<T> fail(T data, ResultCodeEnum resultCodeEnum){
        return build(data, resultCodeEnum);
    }

    public Result<T> message(String msg){
        this.setMessage(msg);
        return this;
    }

    public Result<T> code(Integer code){
        this.setCode(code);
        return this;
    }

    public boolean isSuccess() {
        if(this.getCode().intValue() == ResultCodeEnum.SUCCESS.getCode().intValue()) {
            return true;
        }
        return false;
    }
}
